package com.chu.cloud.api.service;

import com.chu.cloud.dto.MobileSmsCode;
import com.chu.cloud.enums.RedisKeyPrefix;
import com.chu.cloud.enums.sms.SmsCodeType;
import com.chu.cloud.enums.sms.SmsMessageType;
import com.chu.cloud.feign.client.IUserFeignClient;
import com.chu.cloud.rabbit.RabbitConstants;
import com.chu.cloud.rabbit.direct.RabbitDirectSender;
import com.chu.cloud.response.ResponseMessage;
import com.chu.cloud.response.ResultVo;
import com.chu.cloud.util.RedisUtil;
import com.chu.cloud.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Description:
 * @author: TianShu.CHU
 * @CreateDate: 2018-04-05 20:39
 * @Version: 1.0
 */
@Slf4j
@Service
public class MemberService {

    @Autowired
    private RabbitDirectSender directSender;

    @Autowired
    private IUserFeignClient userFeignClient;

    @Autowired
    private StrUtil strUtil;

    /**
     *
     * 发送手机验证码
     * <p>
     *     1.先去redis 查询是否 60s内已经发送
     *     2.未发送: 产生4位验证码 手机号-验证码
     *     3.往消息中心发送消息
     *     4.保存redis
     * @param mobile
     * @param type
     * @return
     */
    public String sendSmsCode(String mobile, SmsMessageType type) {
        String smsCode = RedisUtil.get(RedisKeyPrefix.MOBILE_SMSCODE, mobile, String.class);
        if (StringUtils.isNotBlank(smsCode)){
            return null;
        }
        String randNum = strUtil.getRandNum(4);
        MobileSmsCode msgDto = new MobileSmsCode(mobile,type, SmsCodeType.ALIYUN,randNum);

        log.info("开始发送手机短信消息={}",msgDto);
        directSender.sendDirectMessage(RabbitConstants.DirectQueueNameEnum.MOBILE_CODE_QUEUE,
                msgDto);
        return randNum;
    }

    public ResultVo<String> loginByMobile(String mobile, String validateCode,String ip) {
        ResponseMessage<String> response = userFeignClient.login(mobile, validateCode, ip);
        if (response.getCode() != 200){
            return ResultVo.getError(response.getCode(),response.getMessage());
        }
        return ResultVo.ok(response.getData());
    }


}
